from lxml import etree
from util.selenium.webdriver.common.by import By

# from base.base_method import bm
# from util.db_operate import SaveData
from spider_data.spiderBaseMethod import bm
from util.g import g


def parse_innoinfo(driver=None):
    try:
        innoinfo_loc = (By.LINK_TEXT, '企业创新能力')

        bm.detail_switch_iframe(driver=driver)

        bm.wait(driver=driver, ele_loc=innoinfo_loc)

        driver.find_element(*innoinfo_loc).click()

        inno_tit_loc = (By.CSS_SELECTOR, '#title')
        bm.wait(driver=driver, ele_loc=inno_tit_loc)

        WriteInnovationAbilityForm = {'ripr_iec': '', 'sta_desc': '', 'rdm_desc': '', 'mgt_tech': ''}

        ripr_iec_loc = (By.CSS_SELECTOR, 'div.cxTab ul li:nth-of-type(1)')
        sta_loc = (By.CSS_SELECTOR, 'div.cxTab ul li:nth-of-type(2)')
        rdm_loc = (By.CSS_SELECTOR, 'div.cxTab ul li:nth-of-type(3)')
        mgt_tech_loc = (By.CSS_SELECTOR, 'div.cxTab ul li:nth-of-type(4)')

        bm.click(driver=driver, ele_loc=ripr_iec_loc)
        text = driver.page_source
        tree = etree.HTML(text)
        ripr_iec = tree.xpath("//textarea[@id='Zscqjz']/text()")
        WriteInnovationAbilityForm['ripr_iec'] = bm.handel_long_text(ripr_iec)

        bm.click(driver=driver, ele_loc=sta_loc)
        text = driver.page_source
        tree = etree.HTML(text)

        sta_desc = tree.xpath("//textarea[@id='Kjcgzh']/text()")
        WriteInnovationAbilityForm['sta_desc'] = bm.handel_long_text(sta_desc)

        bm.click(driver=driver, ele_loc=rdm_loc)
        text = driver.page_source
        tree = etree.HTML(text)
        rdm_desc = tree.xpath("//textarea[@id='Jscxgl']/text()")
        WriteInnovationAbilityForm['rdm_desc'] = bm.handel_long_text(rdm_desc)

        bm.click(driver=driver, ele_loc=mgt_tech_loc)
        text = driver.page_source
        tree = etree.HTML(text)
        mgt_tech = tree.xpath("//textarea[@id='Glykj']/text()")
        WriteInnovationAbilityForm['mgt_tech'] = bm.handel_long_text(mgt_tech)

        # # # TODO 这里直接调用 SaveData 中的 save 方法保存数据即可。

        # SaveData().save(table='ent_res_innoinfo', value=innoinfo_item)
        # driver.switch_to.default_content()
        return {"key": "WriteInnovationAbilityForm", "value": WriteInnovationAbilityForm}
    except Exception as err:
        msg = "error: {} file: {} lines: {}".format(err, err.__traceback__.tb_frame.f_globals["__file__"],
                                                    err.__traceback__.tb_lineno)
        g.logger.error(msg)
        raise Exception(msg)

